﻿using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using VoxelBlock;using Vector3Int = VoxelBlock.Vector3Int;
using VoxelBlock.VoxelBlock3D;
using VoxelBlock.VoxelInput;
using VoxelBlock.PackMod;

public class ColorPalatteComponent : MonoBehaviour
{
    public int selectIndex_A;


    [SerializeField]
    public UITexture showPalatte;

    [SerializeField]
    Camera selectCamera;

    [SerializeField]
    LayerMask layerMask;


    [SerializeField]
    Transform selectUVTransform;

    [SerializeField]
    Transform selectGameObject;

    [SerializeField]
    private int editingTexWidth;

    [SerializeField]
    private int editingTexHeigth;

    /// <summary>
    /// 色板层面
    /// </summary>
    [SerializeField]
    [HeaderAttribute("色板层面"), Space(-5)]
    ReadColorHSVComponent readColorHSVComponent;

    void Start()
    {
        selectIndex_A = 1;
        //showPalatte.mainTexture = VoxelEditorMastermind.instance.EditingTex = VoxelEditorMastermind.instance.userTexture;
        OpenTexture();

        VoxelEditorMastermind.instance.OnSelectUVKey = (key) =>
        {
            int pixelUVy = key / VoxelCategories.MAX_UV_X;
            int pixelUVx = key - pixelUVy * VoxelCategories.MAX_UV_X;
            readColorHSVComponent.ShowColor(VoxelEditorMastermind.instance.EditingTex.GetPixel(pixelUVx, pixelUVy));
            selectUVTransform.localPosition = new Vector3(pixelUVx * 30, pixelUVy * 30, 0);
        };
    }
    bool isRun = false;

    void Update ()
    {
        if (isRun)
        {
            Vector3 cursorPos = Input.mousePosition;
            Ray ray = selectCamera.ScreenPointToRay(cursorPos);
            RaycastHit objhit;
            if (Physics.Raycast(ray, out objhit, 100, layerMask))
            {
                if (objhit.collider.transform == selectGameObject)
                {
                    Debug.DrawLine(ray.origin, objhit.point, Color.red, 0.1f);
                    Vector2 pixelUV = objhit.textureCoord;
                    int pixelUVx = (int)(pixelUV.x * editingTexWidth);
                    int pixelUVy = (int)(pixelUV.y * editingTexHeigth);
                    //editingTex.SetPixel(pixelUVx, pixelUVy, Color.red);
                    //editingTex.Apply(true);
                    selectUVTransform.localPosition = new Vector3(pixelUVx * 30, pixelUVy * 30, 0);
                    VoxelEditorMastermind.instance.nowSelectUV = new Vector2Int(pixelUVx, pixelUVy);
                    VoxelEditorMastermind.instance.SetNowSelectUVKey(pixelUVy * VoxelCategories.MAX_UV_X + pixelUVx);
                }
            }
        }

        if (!isRun && Input.GetMouseButtonDown(0))
        {
            Vector3 cursorPos = Input.mousePosition;
            Ray ray = selectCamera.ScreenPointToRay(cursorPos);
            RaycastHit objhit;
            if (Physics.Raycast(ray, out objhit, 100, layerMask))
            {
                if (objhit.collider.transform == selectGameObject)
                {
                    Debug.DrawLine(ray.origin, objhit.point, Color.red, 0.1f);
                    Vector2 pixelUV = objhit.textureCoord;
                    int pixelUVx = (int)(pixelUV.x * editingTexWidth);
                    int pixelUVy = (int)(pixelUV.y * editingTexHeigth);
                    //editingTex.SetPixel(pixelUVx, pixelUVy, Color.red);
                    //editingTex.Apply(true);
                    selectUVTransform.localPosition = new Vector3(pixelUVx * 30, pixelUVy * 30, 0);
                    VoxelEditorMastermind.instance.nowSelectUVKey = pixelUVy * VoxelCategories.MAX_UV_X + pixelUVx;
                    isRun = true;
                }
            }
        }

        if (!Input.GetMouseButton(0))
        {
            isRun = false;
        }

    }

    public void SaveTexture()
    {
        string path = Application.dataPath + "/" + VoxelCategories.USERDATA_PATH + "/" + VoxelCategories.PALATTE_PATH;
        if (Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        File.WriteAllBytes(path + "/Pal" + selectIndex_A + ".png", VoxelEditorMastermind.instance.EditingTex.EncodeToPNG());
    }


    public void OpenTextureIndexU()
    {
        selectIndex_A = 0;
        showPalatte.mainTexture = VoxelEditorMastermind.instance.EditingTex = VoxelEditorMastermind.instance.userTexture;
    }

    public void OpenTextureIndex1()
    {
        selectIndex_A = 1;
        OpenTexture();
    }

    public void OpenTextureIndex2()
    {
        selectIndex_A = 2;
        OpenTexture();
    }

    public void OpenTextureIndex3()
    {
        selectIndex_A = 3;
        OpenTexture();
    }

    Texture2D tempTexture2D;
    private void OpenTexture()
    {
        string path = Application.dataPath + "/" + VoxelCategories.USERDATA_PATH + "/" + VoxelCategories.PALATTE_PATH;
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        path += "/Pal" + selectIndex_A + ".png";
        if (File.Exists(path))
        {
            tempTexture2D = new Texture2D(8, 32);
            tempTexture2D.filterMode = FilterMode.Point;
            tempTexture2D.LoadImage(File.ReadAllBytes(path));
            showPalatte.mainTexture = VoxelEditorMastermind.instance.EditingTex = tempTexture2D;
        }
        else
        {
            showPalatte.mainTexture = VoxelEditorMastermind.instance.EditingTex = Resources.Load<Texture2D>("Texture/Pal" + selectIndex_A);
            File.WriteAllBytes(path, VoxelEditorMastermind.instance.EditingTex.EncodeToPNG());
        }


    }

    public void OpenVoxelFile()
    {
        string path = NewOpenFileName.OpenVoxelFile();
        if (path != null)
        {
            string name = Path.GetExtension(path).ToLower();
            if (name.Equals(".vox"))
            {
                VoxelEditorMastermind.instance.ClearAll();

                Color32[] colors = VoxelEditorMastermind.instance.InputSlabVoxel(path);
                tempTexture2D = new Texture2D(8, 32);
                tempTexture2D.filterMode = FilterMode.Point;

                tempTexture2D.SetPixels32(colors);

                showPalatte.mainTexture = VoxelEditorMastermind.instance.EditingTex = VoxelEditorMastermind.instance.userTexture = tempTexture2D;
                tempTexture2D.Apply();
            }
            else if (name.Equals(".riovox"))
            {
                VoxelEditorMastermind.instance.ClearAll();
                RioVoxelData data = RioVoxelDataIO.Open(path);
                Color32[] colors = new Color32[256];
                if (data.colors.Length <= 256)
                {
                    data.colors.CopyTo(colors, 0);
                }

                tempTexture2D = new Texture2D(8, 32);
                tempTexture2D.filterMode = FilterMode.Point;

                tempTexture2D.SetPixels32(colors);

                showPalatte.mainTexture = VoxelEditorMastermind.instance.EditingTex = VoxelEditorMastermind.instance.userTexture = tempTexture2D;
                tempTexture2D.Apply();
                VoxelEditorMastermind.instance.ReadRiovox(data, null);
                //VoxelPackToMesh.CreateModel(data);
            }

        }
    }

    public void SaveVoxelFile()
    {
        string path = NewOpenFileName.SaveVoxelFile();
        if (path != null)
        {
            string name = Path.GetExtension(path).ToLower();
            if (name.Equals(".vox"))
            {
                VoxelEditorMastermind.instance.SaveMainVoxel(path);
            }
            else if (name.Equals(".riovox"))
            {
                SaveRiovox.Save(path);
            }

        }
    }


}
